package com.example.mybatisfinaltask.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.mybatisfinaltask.pojo.Result;
import com.example.mybatisfinaltask.utils.JwtUtils;
import com.github.pagehelper.util.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;
        String url=req.getRequestURI().toString();
        log.info("请求url:{}",url);
        if(url.contains("login")){
            log.info("登录操作,放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String jwt=req.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空，返回未登录信息");
            Result error=Result.error("NOT_LOGIN");
            //手动转换;对象-》json
            String notLogin= JSONObject.toJSONString(error);
            System.out.println("转换后的json对象"+notLogin);
            //将json格式的result结果返回给前端
            resp.getWriter().write(notLogin);
            return;
        }
        //解析令牌，解析失败则返回错误信息，否则放行
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");
            //手动转换;对象-》json
            String notLogin= JSONObject.toJSONString(error);
            System.out.println("转换后的json对象"+notLogin);
            //将json格式的result结果返回给前端
            resp.getWriter().write(notLogin);
            return;
        }
        System.out.println("令牌是"+jwt);
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
